package com.campus_activity.campus_activity.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus_activity.campus_activity.common.PageResult;
import com.campus_activity.campus_activity.constant.HttpStatus;
import com.campus_activity.campus_activity.domain.dto.ActivityDTO;
import com.campus_activity.campus_activity.domain.dto.ActivityPageQueryDTO;
import com.campus_activity.campus_activity.domain.po.Activity;
import com.campus_activity.campus_activity.domain.po.ActivityImg;
import com.campus_activity.campus_activity.domain.po.User;
import com.campus_activity.campus_activity.domain.po.UserActivity;
import com.campus_activity.campus_activity.domain.vo.ActivityDetailVO;
import com.campus_activity.campus_activity.domain.vo.ActivityTicketVO;
import com.campus_activity.campus_activity.domain.vo.ActivityVO;
import com.campus_activity.campus_activity.enums.ActivityStatusEnum;
import com.campus_activity.campus_activity.exception.BusinessException;
import com.campus_activity.campus_activity.mapper.ActivityImgMapper;
import com.campus_activity.campus_activity.mapper.UserActivityMapper;
import com.campus_activity.campus_activity.service.ActivityService;
import com.campus_activity.campus_activity.mapper.ActivityMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 73493
 * @description 针对表【t_activity(活动表)】的数据库操作Service实现
 * @createDate 2023-04-24 17:04:42
 */
@Service
@RequiredArgsConstructor
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity>
        implements ActivityService {

    private final ActivityMapper activityMapper;

    private final ActivityImgMapper activityImgMapper;

    private final UserActivityMapper userActivityMapper;


    @Override
    public PageResult<ActivityVO> listActivity(ActivityPageQueryDTO activityPageQueryDTO) {
        String activityName = activityPageQueryDTO.getActivityName();
        //分页查询
        IPage<ActivityVO> page = new Page<>();
        page.setSize(activityPageQueryDTO.getPageSize());
        page.setCurrent(activityPageQueryDTO.getCurrentPage());
        //分页条件查询
        page.setRecords(activityMapper.listActivity(page, activityName));
        PageResult<ActivityVO> pageResult = new PageResult(page);
        return pageResult;
    }

    //TODO 完成业务
    @Override
    @Transactional
    public boolean publishActivity(ActivityDTO activityDTO) {
        //获取当前用户的id
//        Long authorId = StpUtil.getLoginIdAsLong();
        Long authorId = 1L;
        Activity activity = new Activity();
        //复制拷贝并存入数据库中
        BeanUtil.copyProperties(activityDTO, activity);
        activity.setAuthorId(authorId);

        //如果保存成功则继续保存活动相关图片
        boolean saveFlag = this.save(activity);
        List<String> activityImgUrlList = activityDTO.getActivityImgList();

        //批处理成功标志
        boolean flag = true;
        //保存成功且需要传入图片
        if (saveFlag && activityImgUrlList.size() > 0) {
            //TODO 对接七牛云OSS存储图片暂时只是模拟
            //批量插入
            List<ActivityImg> activityImgList = new ArrayList<>();
            //如果存在图片
            for (int i = 0; i < activityImgUrlList.size(); i++) {
                String url = activityImgUrlList.get(i);
                //获取对象
                ActivityImg activityImg = new ActivityImg();
                activityImg.setActivityId(activity.getId());
                activityImg.setImgUrl(url);
                activityImgList.add(activityImg);
            }
            flag = activityImgMapper.batchSave(activityImgList);
        }
        return flag;
    }

    @Override
    public ActivityDetailVO getActivityDetail(Long id) {
        //TODO  获取活动详细信息
        ActivityDetailVO activityDetailVO = activityMapper.getActivityDetailById(id);
        if (activityDetailVO == null) {
            throw new BusinessException(HttpStatus.ERROR, "该活动不存在!");
        }
        //TODO 是否参加项目状态？
        return activityDetailVO;
    }

    @Override
    @Transactional
    public boolean cancelActivity(Long id) {
        //TODO 修改用户id
//        Long userId = StpUtil.getLoginIdAsLong();
        Long userId = 1L;
        //删除对应的活动,删除对应的活动记录
        LambdaQueryWrapper<UserActivity> userActivityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userActivityLambdaQueryWrapper.eq(UserActivity::getActivityId, id);
        userActivityLambdaQueryWrapper.eq(UserActivity::getUserId, userId);
        userActivityMapper.delete(userActivityLambdaQueryWrapper);
        //TODO 删除对应的活动图片 oss删除
        LambdaQueryWrapper<ActivityImg> activityImgLambdaQueryWrapper = new LambdaQueryWrapper<>();
        activityImgLambdaQueryWrapper.eq(ActivityImg::getActivityId, id);
        activityImgMapper.delete(activityImgLambdaQueryWrapper);
        boolean flag = this.removeById(id);
        return flag;
    }

    @Override
    @Transactional
    public boolean exitActivity(Long id) {
        //获取活动
//        Long userId = StpUtil.getLoginIdAsLong();
        //TODO 修改用户id
        Long userId = 1L;
        LambdaQueryWrapper<UserActivity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserActivity::getStatus, ActivityStatusEnum.ATTEND.getStatus());
        lambdaQueryWrapper.eq(UserActivity::getUserId, userId);
        lambdaQueryWrapper.eq(UserActivity::getActivityId, id);

        //获取记录
        UserActivity userActivity = userActivityMapper.selectOne(lambdaQueryWrapper);

        if (userActivity == null) {
            throw new BusinessException(HttpStatus.ERROR, "你未参加该活动!");
        }

        int status = userActivity.getStatus();

        //如果已经参加
        if (ActivityStatusEnum.ATTEND.getStatus() != status) {
            throw new BusinessException(HttpStatus.ERROR, "你未参加该活动!");
        }

        //将活动已有人数人数 - 1
        boolean flag = this.update().setSql("has_number = has_number - 1").
                eq("id", id)
                .gt("has_number", 0)
                .update();

        //退出活动更改状态
        userActivity.setStatus(ActivityStatusEnum.CANCEL.getStatus());
        int i = userActivityMapper.updateById(userActivity);
        return flag && i == 1;
    }

    @Override
    public PageResult<ActivityVO> listActivityPublishHistory(ActivityPageQueryDTO activityPageQueryDTO) {
        //分页查询
        IPage<ActivityVO> page = new Page<>();
        page.setSize(activityPageQueryDTO.getPageSize());
        page.setCurrent(activityPageQueryDTO.getCurrentPage());

        //分页条件查询
        //TODO 修改用户id
        Long userId = 1L;
        String activityName = activityPageQueryDTO.getActivityName();
        page.setRecords(activityMapper.listActivityPublishHistory(page, activityName, userId));
        PageResult<ActivityVO> pageResult = new PageResult(page);
        return pageResult;
    }


    @Override
    public ActivityTicketVO getActivityTicket(Long id) {
        //查询用户id
        //TODO 更换用户id
//        Long userId = StpUtil.getLoginIdAsLong();
        Long userId = 1L;

        return null;
    }

    @Override
    public PageResult<ActivityVO> listActivityHistory(ActivityPageQueryDTO activityPageQueryDTO) {
        //查询用户id
//        Long userId = StpUtil.getLoginIdAsLong();
        Long userId = 1L;
        String activityName = activityPageQueryDTO.getActivityName();
        //分页查询
        IPage<ActivityVO> page = new Page<>();
        page.setSize(activityPageQueryDTO.getPageSize());
        page.setCurrent(activityPageQueryDTO.getCurrentPage());

        //分页条件查询
        page.setRecords(activityMapper.listActivityHistory(page, userId, activityName));
        PageResult<ActivityVO> pageResult = new PageResult(page);
        return pageResult;
    }


}




